package com.syj.qdp.framework.web.serializer.factory;

import com.fasterxml.jackson.databind.JsonSerializer;
import com.syj.qdp.framework.common.consumer.ThridConsumer;
import com.syj.qdp.framework.web.serializer.JsonSerializerGenerator;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Lyon
 */
public class JsonSerializerFactory {

    private static final ConcurrentHashMap<Class<?>,JsonSerializer<?>> SERIALIZERS = new ConcurrentHashMap<>();

    public static <T>JsonSerializer<T> getOrIgnore(Class<T> clazz)  {
        JsonSerializer<T> serializer = (JsonSerializer<T>) SERIALIZERS.get(clazz);
        return serializer == null ? register(clazz) : serializer;
    }

    private static <T> JsonSerializer<T> register(Class<T> clazz) {
        return register(clazz,null);
    }

    /**
     *
     * @param clazz
     * @param serializer {@link JsonSerializerGenerator#generate(Class, ThridConsumer)}
     * @param <T>
     * @return
     */
    public static <T> JsonSerializer<T> register(Class<T> clazz , JsonSerializer<T> serializer) {
        if (serializer == null) {
            serializer = JsonSerializerGenerator.generateIgnore(clazz);
        }
        SERIALIZERS.putIfAbsent(clazz,serializer);
        return serializer;
    }

}
